package com.sq.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;

public class BigDecimalUtil {

    /**
     * 获取格式化的字符串
     * 
     */
    public static String getFormatStr(BigDecimal number) {
        number = format(number);
        DecimalFormat format = new DecimalFormat("0.##");
        return format.format(number.doubleValue());
    }

    public static BigDecimal format(BigDecimal number) {
        if (number.scale() > 2) {
            return number.setScale(2, BigDecimal.ROUND_DOWN);
        }
        return number;
    }

    public static BigDecimal multiply(Number a, Number b) {
        BigDecimal x = getBigDecimal(a);
        BigDecimal y = getBigDecimal(b);
        return x.multiply(y);
    }

    public static BigDecimal divide(Number a, Number b) {
        return divide(a, b, 0, RoundingMode.HALF_UP);
    }

    /**
     * @param roundingMode
     *            RoundingMode.HALF_UP 四舍五入
     */
    public static BigDecimal divide(Number a, Number b, RoundingMode roundingMode) {
        return divide(a, b, 0, roundingMode);
    }

    public static BigDecimal divide(Number a, Number b, int scale, RoundingMode roundingMode) {
        BigDecimal x = getBigDecimal(a);
        BigDecimal y = getBigDecimal(b);
        if (y.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }
        return x.divide(y, scale, roundingMode);
    }

    /**
     * 判断能否整除
     *
     * @param dividend 被除数
     * @param divisor  除数
     * @return
     */
    public static boolean isDivisible(BigDecimal dividend, BigDecimal divisor) {
        BigDecimal remainder = dividend.remainder(divisor);
        if (remainder.compareTo(BigDecimal.ZERO) == 0) {
            return true;
        } else {
            return false;
        }
    }

    private static BigDecimal getBigDecimal(Number n) {
        if (n instanceof BigDecimal) {
            return (BigDecimal) n;
        } else if (n instanceof Integer) {
            return new BigDecimal((Integer) n);
        } else if (n instanceof Long) {
            return new BigDecimal((Long) n);
        } else {
            return new BigDecimal(String.valueOf(n));
        }
    }

}
